<?php
session_start();
if (!$_SESSION['user']){
    header('Location: login.php');
    return;
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>查询通讯录</title>
    <style>
        a{
            color: gray;
            text-decoration: none;
            cursor: pointer;
        }
        a:hover{
            color:red;
        }
        .new{
            text-align: right;
            width:480px;
        }
        h1{
            color:red;
        }
        table{
            width:480px;
            border:4px double red;
            border-spacing: 0;
        }
        th, td{
            border-bottom: 1px dotted red;
            border-right: 1px dotted red;
            padding: 6px 10px;
            text-align: center;
        }
        .status{
            text-align: right;
            width: 480px;
            margin: 6px 0;
            display: flex;
        }
        .status>p:nth-child(2){
            color: red;
            flex-grow: 1;
            text-align: left;
        }
        p{
            margin: 0;
        }
    </style>
</head>
<body>
<h1>通讯录信息</h1>
<div class="status">
    <p>欢迎你:</p>
    <p><?=$_SESSION['user']['xh'].$_SESSION['user']['name']?></p>
    <a href="logout.php">注销</a>
</div>
<?php
$db = new PDO("mysql:host=localhost; dbname=db2;", 'root', 'root');
$db -> setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
$ps = $db -> query('select * from students');
echo "<table>";
echo "<tr><th>学号</th><th>姓名</th><th>电话</th><th>管理</th></tr>";
foreach ($ps as $r) {
    echo "<tr data-xh='",urlencode($r['xh']),"'><td>{$r['xh']}</td><td>{$r['name']}</td><td>{$r['tel']}</td><td>";
    if ($r['xh'] === $_SESSION['user']['xh'] || $_SESSION['user']['isAdmin']){
        echo "<a>删除</a> <a>修改</a>";
    }
    echo "</td></tr>";
}
echo '</table>'
?>
<script>
    document.querySelectorAll('td>a').forEach(a => {
        a.addEventListener('click',async (e) => {
            let tr = a.parentElement.parentElement
            let xh = tr.getAttribute('data-xh')
            console.log(a,a.innerText,xh)
            if (a.innerText === '删除'){
                console.log('执行删除操作' + xh)
                let response = await fetch('delete2.php?xh=' + xh)
                let result = await response.json()
                console.log(result)
                if (result.ok){
                    if (result.logout){
                        location.href = 'login.php'
                    }else {
                        tr.remove()
                    }
                }else {
                    alert(result.msg)
                }
            } else if (a.innerText === '修改'){
                console.log('执行修改操作' + xh)
                fetch('.php')
            }
        })
    })
</script>
</body>
</html>